package com.music.utilbean;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.xml.parsers.ParserConfigurationException;

public class SearchUtil {
	public static void hideInputMethod(View view) {//点击隐藏输入法框
		InputMethodManager imm = (InputMethodManager) KuwoApplication.context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm.isActive()) {
			imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	private static final int    SIZE = 20;
	private static final String URL  = Contant.BAIDU_URL + Contant.BAIDU_SEARCH;
	private static SearchUtil            searchUtil;
	private        ExecutorService       mThreadPool;
	public         OnSearchMusicListener mListener;

	public synchronized static SearchUtil getInstance() {
		if (searchUtil == null) {

			try {
				searchUtil = new SearchUtil();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			}

		}
		return searchUtil;
	}

	private SearchUtil() throws ParserConfigurationException {
		mThreadPool = Executors.newSingleThreadExecutor();
	}

	public SearchUtil setListener(OnSearchMusicListener l) {
		mListener = l;
		return this;
	}

	public void search(final String key, final int page) {
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
					case Contant.SUCCESS:
						if (mListener != null) {
							mListener.onSearchResult((ArrayList<SearchResult>) msg.obj);
						}
						break;
					case Contant.FAILED:
						if (mListener != null) {
							mListener.onSearchResult(null);
						}
						break;
				}
			}
		};
		mThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				ArrayList<SearchResult> results = getMusicList(key, page);
				if (results == null) {
					handler.sendEmptyMessage(Contant.FAILED);
					return;
				}
				handler.obtainMessage(Contant.SUCCESS, results).sendToTarget();
			}
		});
	}

	//Jsoup请求网络数据
	private ArrayList<SearchResult> getMusicList(final String key, final int page) {
		final String start = String.valueOf((page - 1) * SIZE);
		try {
			Document doc = Jsoup.connect(URL).data("key", key, "start", start, "size", String.valueOf(SIZE))
					.userAgent(Contant.USER_AGENT).timeout(60 * 1000).get();
			Elements songTitles = doc.select("div.song-item.clearfix");
			//System.out.println(doc);
			Elements songInfos;
			ArrayList<SearchResult> searchResults = new ArrayList<SearchResult>();
			TAG:
			for (Element song : songTitles) {
				songInfos = song.getElementsByTag("a");
				SearchResult searchResult = new SearchResult();
				for (Element info : songInfos) {

					//收费的歌曲
					if (info.attr("href").startsWith("http://y.baidu.com/song/")) {
						continue TAG;
					}
					//跳转百度音乐盒
					if (info.attr("href").equals("#") && !TextUtils.isEmpty(info.attr("data-songdata"))) {
						continue TAG;
					}
					//歌曲链接
					if (info.attr("href").startsWith("/song")) {
						searchResult.setMusicname(info.text());
						searchResult.setUrl(info.attr("href"));
						searchResult.setMusicId(info.attr("href").substring(info.attr("href").lastIndexOf("/") + 1));
						System.out.println(info.attr("href").substring(info.attr("href").lastIndexOf("/") + 1));

					}
					//歌手链接
					if (info.attr("href").startsWith("/data")) {
						searchResult.setArtist(info.text());
					}
					//专辑链接
					if (info.attr("href").startsWith("/album")) {
						searchResult.setAlbum(info.text().replaceAll("<|>", ""));
					}
				}
				searchResults.add(searchResult);
			}
			return searchResults;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public interface OnSearchMusicListener {
		public void onSearchResult(ArrayList<SearchResult> results);
	}
}
